﻿Imports System.IO
Imports ADOConnection
Imports System.Globalization
Imports CrystalDecisions.CrystalReports.Engine

Public Class frmViewPhieuNX
    Private sdaSLNX As IDbDataAdapter
    Private sdaDPNX As IDbDataAdapter
    Private bsDPNX As BindingSource
    Private bsSLNX As BindingSource
    Private dsDataSet As DataSet
    Public mDpnx_Id As Integer = -1
    Public mSelectedIndex As Integer = -1
    Dim enumNX As enumDOITUONG = enumDOITUONG.TINHCHATNHAP
    'Chi cho phep user go duoc 1 trong 2 ky tu 'N' hoac 'X'
    Public isMaxCharNum As Boolean 'Bien dung cho event txtNX_Keydown, txtNX_Keyup

    'Public Sub CheckSystemDateFormat()
    '    'Get the Current System culture.
    '    Dim ci As CultureInfo = CultureInfo.CurrentCulture
    '    Dim dtfi As DateTimeFormatInfo = ci.DateTimeFormat
    '    Dim SystemDateTimePatterns() As String = New String(250) {}
    '    Dim i As Integer = 0
    '    For Each name As String In dtfi.GetAllDateTimePatterns("d")
    '        SystemDateTimePatterns(i) = name
    '        i += 1
    '    Next
    '    Dim myDateTimeFormat() As String = {"dd-MMM-yy", "dd-MMM-yyyy"}
    '    If (myDateTimeFormat(0).Equals(SystemDateTimePatterns(0)) Or myDateTimeFormat(1).Equals(SystemDateTimePatterns(0))) Then
    '        MessageBox.Show("Your System DateTime Format " + SystemDateTimePatterns(0) + " is OK")
    '    Else
    '        MessageBox.Show("Your System DateTime Format is: " + SystemDateTimePatterns(0) + "\n" + "Required DateTime Format: dd-MMM-yy Or dd-MMM-yyyy")
    '    End If
    'End Sub

    Private Sub frmViewPhieuNhap_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            'ToolStripStatusLabel1.Text = "F1:Thêm   F2:Sửa  F3:Xóa  F4:Tìm kiếm  F6:In"
            ' Create columns for the items and subitems.
            'lvDMPhieu.Columns.Add("Mã", 0, HorizontalAlignment.Center)
            lvDMPhieu.Columns.Add("NX", 25, HorizontalAlignment.Center)
            lvDMPhieu.Columns.Add("Số phiếu", 65, HorizontalAlignment.Left)
            lvDMPhieu.Columns.Add("TT", 35, HorizontalAlignment.Center)
            lvDMPhieu.Columns.Add("Ngày", 70, HorizontalAlignment.Center)
            lvDMPhieu.Columns.Add("Giá trị", 110, HorizontalAlignment.Right)

            sdaDPNX = g_objConnFactory.CreateAdapter
            sdaSLNX = g_objConnFactory.CreateAdapter
            RefreshForm()
        Catch ex As Exception
            MessageBox.Show(ex.ToString(), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#Region "Events"

#Region "Draw ListView"
    Private Sub lvDMPhieu_DrawColumnHeader(ByVal sender As Object, ByVal e As DrawListViewColumnHeaderEventArgs) Handles lvDMPhieu.DrawColumnHeader
        Dim sf As New StringFormat()
        Try
            sf.Alignment = StringAlignment.Center
            ' Draw the standard header background.
            e.DrawBackground()
            ' Draw the header text.
            Dim headerFont As New Font("Courier New", 9, FontStyle.Bold)
            e.Graphics.DrawString(e.Header.Text, headerFont, Brushes.Black, e.Bounds, sf)
            'e.Graphics.DrawString(e.Header.Text, e.Font, Brushes.Black, e.Bounds, sf)
        Catch ex As Exception
        Finally
            sf.Dispose()
        End Try
    End Sub

    Private Sub lvDMPhieu_DrawSubItem(ByVal sender As Object, ByVal e As DrawListViewSubItemEventArgs) Handles lvDMPhieu.DrawSubItem
        Dim brText As Brush
        e.DrawBackground()
        Try
            'Neu la Selected Item thi to mau Red, nguoc lai to theo BCTH
            If (e.ItemState And DrawItemState.Selected) = DrawItemState.Selected Then
                brText = Brushes.Red
            Else
                Select Case Me.lvDMPhieu.Items(e.ItemIndex).SubItems(3).Text
                    Case "KH"
                        brText = Brushes.Black
                    Case "TCT"
                        brText = Brushes.Blue
                    Case "TCSL"
                        brText = Brushes.Violet
                    Case Else
                        brText = Brushes.DarkOrange
                End Select
            End If
            ' Draw the subitem text in red to highlight it. 
            Dim sf As New StringFormat()
            If e.Header.Index = 5 Then
                sf.Alignment = StringAlignment.Far
                e.Graphics.DrawString(e.SubItem.Text, Me.lvDMPhieu.Font, brText, e.Bounds, sf)
            Else
                sf.Alignment = StringAlignment.Center
                e.Graphics.DrawString(e.SubItem.Text, Me.lvDMPhieu.Font, brText, e.Bounds, sf)
            End If
        Catch ex As Exception

        End Try
    End Sub
#End Region

    Private Sub btnLoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoc.Click
        Dim frm As New frmLocPhieu
        frm.ShowDialog()
        Init()
        FocusListView()
    End Sub

    Private Sub lvDMPhieu_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvDMPhieu.SelectedIndexChanged
        For Each item As ListViewItem In Me.lvDMPhieu.SelectedItems
            mSelectedIndex = item.Index
            enumNX = enumDoiTuong.TINHCHATXUAT
            Select Case item.SubItems(1).Text
                Case "N"
                    lblTitle.Text = "PHIẾU NHẬP: "
                    enumNX = enumDOITUONG.TINHCHATNHAP
                Case Else
                    lblTitle.Text = "PHIẾU XUẤT: "
            End Select
            mDpnx_Id = item.SubItems(0).Text
            lblTitle.Text &= item.SubItems(2).Text + "  (" + item.SubItems(3).Text & ")"
            RefreshThongTinPhieu()
            Application.DoEvents()
        Next
    End Sub

    Private Sub OpenFrmPhieuNX()
        Dim objPhieu As CPhieuNX = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        If objPhieu.BCTH = 2 And g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
            ShowMessages("Bạn không có quyền cập nhật phiếu tài chính đã xác nhận.")
            Exit Sub
        ElseIf g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.CHUNHIEMBAN) _
            Or g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINHSL) Then
            ShowMessages("Quyền cập nhật phiếu không có.")
            Exit Sub
        End If

        If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
            Dim frm As New frmPhieuNXNoiBo
            frm.fViewPhieuNX = Me
            frm.objPhieuXuat = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
            frm.objPhieuNhap = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
            frm.MdiParent = Me.MdiParent
            frm.Show()
        ElseIf CDoiTuongs.KiemTraTCNX(enumTCNX.DCSS, objPhieu.TCNX) Then
            Dim frm As New frmPhieuNXDCSS
            frm.fViewPhieuNX = Me
            frm.objPhieu = objPhieu
            frm.MdiParent = Me.MdiParent
            frm.Show()
        Else
            Dim frm As New frmPhieuNX
            frm.fViewPhieuNX = Me
            frm.objPhieu = objPhieu
            frm.MdiParent = Me.MdiParent
            frm.Show()
        End If
    End Sub

    Private Sub lvDMPhieu_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvDMPhieu.DoubleClick
        OpenFrmPhieuNX()
    End Sub

    Private Sub lvDMPhieu_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles lvDMPhieu.KeyDown
        If e.KeyCode = Keys.Enter Then
            OpenFrmPhieuNX()
        ElseIf e.KeyCode = Keys.F6 Then
            InPhieu()
        ElseIf e.KeyCode = Keys.F5 Then
            RefreshForm()
        ElseIf e.KeyCode = Keys.Delete Then
            mnuItemXoa_Click(Nothing, Nothing)
        ElseIf e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub gridCTPhieu_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridCTPhieu.CellDoubleClick
        Dim frm As New frmQuanLyLoHang(gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("lk").Value.ToString(), gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("makho").Value.ToString(), CInt(gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("mathang_id").Value))
        frm.ShowDialog(Me)
    End Sub

    Private Sub gridCTPhieu_ColumnHeaderMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles gridCTPhieu.ColumnHeaderMouseClick
        Dim count As Integer = 0
        For Each dvRow As DataGridViewRow In gridCTPhieu.Rows
            dvRow.HeaderCell.Value = (count + 1).ToString
            count += 1
        Next
    End Sub

    Private Sub Controls_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gridCTPhieu.KeyDown, gridPhieu.KeyDown, _
    btnLoc.KeyDown, txtLoc.KeyDown
        If e.KeyCode = Keys.Enter And sender Is gridCTPhieu Then
            gridCTPhieu_CellDoubleClick(Nothing, Nothing)
        ElseIf e.KeyCode = Keys.F5 Then
            RefreshForm()
        ElseIf e.KeyCode = Keys.F6 Then
            'In
            InPhieu()
        ElseIf e.KeyCode = Keys.Q And e.Modifiers = Keys.Control Then
            FocusListView()
        ElseIf e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub
#End Region

#Region "Functions"
    Public Sub Init()
        Dim arrDMPhieuNX As ArrayList = CPhieuNXs.GetPhieuNXList(mySqlDK)
        lblSL.Text = arrDMPhieuNX.Count
        txtLoc.Text = myShowDK

        'add data in ListView
        lvDMPhieu.Items.Clear()
        mDpnx_Id = -1
        Dim item As ListViewItem
        For Each objPhieu As CPhieuNX In arrDMPhieuNX
            item = New ListViewItem(objPhieu.DPNX_ID)
            item.SubItems.Add(objPhieu.NX)
            item.SubItems.Add(objPhieu.SOPHIEU)
            If objPhieu.KYQT > 1 Then
                item.SubItems.Add(CBCTHs.GetBCTH(objPhieu.BCTH, objPhieu.TCSL).NAME + (objPhieu.KYQT - 1).ToString())
            Else
                item.SubItems.Add(CBCTHs.GetBCTH(objPhieu.BCTH, objPhieu.TCSL).NAME)
            End If
            item.SubItems.Add(objPhieu.NGAY.ToString(FormatDateStyle()))
            item.SubItems.Add(objPhieu.TGIATRI.ToString(FormatMoneyStyle()))
            lvDMPhieu.Items.Add(item)
        Next

        'For Each objPhieu As CPhieuNX In arrDMPhieuNX
        '    item = New ListViewItem(objPhieu.DPNX_ID)
        '    item.Name = objPhieu.DPNX_ID.ToString()
        '    item.
        '    'NX
        '    Dim subItem As New ListViewItem.ListViewSubItem()
        '    subItem.Name = "NX"
        '    subItem.Text = objPhieu.NX

        '    subItem = New ListViewItem.ListViewSubItem()

        '    item.SubItems.Add(objPhieu.SOPHIEU)
        '    If objPhieu.KYQT > 1 Then
        '        item.SubItems.Add(CBCTHs.GetBCTH(objPhieu.BCTH, objPhieu.TCSL).NAME + (objPhieu.KYQT - 1).ToString())
        '    Else
        '        item.SubItems.Add(CBCTHs.GetBCTH(objPhieu.BCTH, objPhieu.TCSL).NAME)
        '    End If
        '    item.SubItems.Add(objPhieu.NGAY.ToString(FormatDateStyle()))
        '    item.SubItems.Add(objPhieu.TGIATRI.ToString(FormatMoneyStyle()))
        '    lvDMPhieu.Items.Add(item)
        'Next
    End Sub

    Public Sub FormatGridStyleDPNX()
        If enumNX = enumDoiTuong.TINHCHATNHAP Then
            gridPhieu.DataSource = dsDataSet.Tables("PhieuNhapInfo")
        Else
            gridPhieu.DataSource = dsDataSet.Tables("PhieuXuatInfo")
        End If

        With gridPhieu
            .AutoResizeRows()
            .Columns(0).DefaultCellStyle.BackColor = Color.Black
            .Columns(0).DefaultCellStyle.ForeColor = Color.SpringGreen
            .Columns(0).DefaultCellStyle.Font = New Font(gridPhieu.DefaultCellStyle.Font.FontFamily, 9, FontStyle.Bold)

            .Columns(1).DefaultCellStyle.ForeColor = Color.DarkBlue

            .Columns(2).DefaultCellStyle.BackColor = Color.Black
            .Columns(2).DefaultCellStyle.ForeColor = Color.SpringGreen
            .Columns(2).DefaultCellStyle.Font = New Font(gridPhieu.DefaultCellStyle.Font.FontFamily, 9, FontStyle.Bold)

            .Columns(3).DefaultCellStyle.ForeColor = Color.DarkBlue

            .Columns(0).Width = Int(gridPhieu.Width / 6) + 40
            .Columns(1).Width = gridPhieu.Columns(0).Width + 5
            .Columns(2).Width = gridPhieu.Columns(0).Width
        End With
        With gridPhieu.DefaultCellStyle
            .SelectionForeColor = Color.Yellow
        End With
        'Khoi tao gridPhieu
        If mDpnx_Id >= 0 Then
            CPhieuNXs.FillDataSetDPNX(mDpnx_Id, bsDPNX, dsDataSet)
        End If
    End Sub

    Public Sub FormatGridStyleSLNX()
        'Khoi tao gridCTPhieu
        bsSLNX.Filter = "DPNX_ID = " + mDpnx_Id.ToString
        bsSLNX.Sort = "SLNX_ID ASC"
        gridCTPhieu.DataSource = bsSLNX

        For count As Integer = 0 To gridCTPhieu.RowCount - 1
            gridCTPhieu.Rows(count).HeaderCell.Value = (count + 1).ToString
        Next

        With gridCTPhieu
            .RowHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns.Item("slnx_id").Visible = False

            .Columns.Item("mathang_id").Visible = False
            .Columns.Item("mathang_id").Frozen = True

            .Columns.Item("dpnx_id").Visible = False

            .Columns.Item("makho").Visible = False
            .Columns.Item("makho").Frozen = True

            .Columns.Item("ma").Visible = False
            .Columns.Item("ma").Frozen = True

            .Columns.Item("code").Visible = False
            .Columns.Item("code").Frozen = True

            .Columns.Item("lk").Visible = False
            .Columns.Item("ngtton").Visible = False
            .Columns.Item("slss11").Visible = False
            .Columns.Item("slkk11").Visible = False
            .Columns.Item("sltonkh").Visible = False
            .Columns.Item("sltonth").Visible = False
            .Columns.Item("sltonss").Visible = False

            With .Columns.Item("kho")
                .Width = 70
                .HeaderText = "Kho"
                .Frozen = True
            End With

            With .Columns.Item("ten")
                .Width = 150
                .HeaderText = "Tên hàng"
                .Frozen = True
            End With

            With .Columns.Item("dvt")
                .Width = 40
                .HeaderText = "Đvt"
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End With

            With .Columns.Item("lo")
                .Width = 80
                .HeaderText = "Lô hàng"
            End With

            With .Columns.Item("gle")
                .HeaderText = "Giá lẻ"
                .Width = 60
                .DefaultCellStyle.Format = FormatMoneyStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With

            With .Columns.Item("hansd")
                .Width = 50
                .HeaderText = "HSD"
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End With

            With .Columns.Item("h")
                .Width = 30
                .HeaderText = "CCL"
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End With

            With .Columns.Item("slkh")
                .HeaderText = "SLKH"
                .Width = 60
                .DefaultCellStyle.Format = FormatQuantityStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With

            With .Columns.Item("slth")
                .HeaderText = "SLTH"
                .Width = 60
                .DefaultCellStyle.Format = FormatQuantityStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With

            With .Columns.Item("thanhtien")
                .HeaderText = "Thành tiền"
                .Width = 100
                .DefaultCellStyle.Format = FormatMoneyStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With
            With .Columns.Item("ghichu")
                .Width = 100
                .HeaderText = "Ghi chú"
            End With
        End With
    End Sub

    Public Sub RefreshThongTinPhieu()
        Try
            FormatGridStyleDPNX()
            FormatGridStyleSLNX()
            'If Me.WindowState = FormWindowState.Maximized Then
            '    gridCTPhieu.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
            'End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString(), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Public Sub FocusListView()
        ControlSetFocus(lvDMPhieu)
        Try
            If lvDMPhieu.Items.Count > 0 Then
                If mSelectedIndex > 0 Then
                    lvDMPhieu.Items(mSelectedIndex).Selected = True
                Else
                    lvDMPhieu.Items(0).Selected = True
                End If
            End If
        Catch ex As Exception
            'lvDMPhieu.Items(0).Selected = True
        End Try
    End Sub

    Public Sub InitDataSet()
        bsDPNX = New BindingSource
        bsSLNX = New BindingSource
        dsDataSet = Nothing

        CPhieuNXs.CreateDataSetDPNX(dsDataSet)
        bsDPNX.DataSource = dsDataSet.Tables("PhieuNX")
        CSLNXs.CreateDataSetSLNX(sdaSLNX, dsDataSet)
        bsSLNX.DataSource = dsDataSet.Tables(3)
    End Sub

    Public Sub RefreshForm()
        InitDataSet()
        Init()
        RefreshThongTinPhieu()
        FocusListView()
    End Sub
#End Region

    Public Sub InPhieu()
        Dim objSelectedPhieu As CPhieuNX = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        Dim strSql As String
        strSql = "select * from viewNhapXuat where DPNX_ID = " & objSelectedPhieu.DPNX_ID.ToString() & _
                 " order by kho, ma"
        Dim ds As DataSet
        Dim count As Integer = 0
        Dim RowCount As Integer = 0
        ds = BaseDB.ExecSql_DataSet(strSql)
        'Dem so dong cua mat hang trong phieu
        count = ds.Tables(0).Rows.Count * 2
        'Dem so dong cua kho trong phieu
        strSql = "select kho,count(*) from viewNhapXuat where DPNX_ID = " & objSelectedPhieu.DPNX_ID.ToString() & _
                 " group by kho order by kho"
        count += BaseDB.ExecSql_DataSet(strSql).Tables(0).Rows.Count
        Dim ten_dvgn, ten_lk, ten_tcnx As String
        ten_dvgn = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, objSelectedPhieu.DVGN).Ten
        ten_lk = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.LOAIKHO, objSelectedPhieu.LK).Ten
        Dim nnreport As New rptPhieuNhapKho
        nnreport.SetDataSource(ds.Tables(0))
        nnreport.SetParameterValue("ten_dvgn", ten_dvgn)
        nnreport.SetParameterValue("ten_lk", ten_lk)
        'tinh tong thanh tien da lam tron.
        strSql = "select sum(isnull(THANHTIEN,0)) from viewNhapXuat where DPNX_ID = " & objSelectedPhieu.DPNX_ID.ToString()
        Dim tongtien As Double
        tongtien = BaseDB.ExecSql_DataValue(strSql)
        nnreport.SetParameterValue("tien_chu", DoiSoRaChu(tongtien))
        If (objSelectedPhieu.NX = "N") Then
            ten_tcnx = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATNHAP, objSelectedPhieu.TCNX).Ten
            nnreport.SetParameterValue("loai_phieu", "N")
        Else
            ten_tcnx = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATXUAT, objSelectedPhieu.TCNX).Ten
            nnreport.SetParameterValue("loai_phieu", "X")
        End If
        nnreport.SetParameterValue("ten_tcnx", ten_tcnx)
        'Tong kich thuoc 1 trang A4 ~ 11154 (tinh dua vao tong cac section va cac mat hang co toi da)
        '1) Section1: 2880
        '2) Section2: 1114
        '3) PageHeaderSection1: 1080
        '       _ GroupHeaderSection2: 327 * N (N: So Kho duoc nhap vao trong phieu)
        '           + Section3: 654*N (N: So mat hang trong phieu)
        '4) ReportFooterSection2: 654
        '5) ReportFooterSection1: 3884


        Dim Section1 As Section = nnreport.ReportDefinition.Sections("Section1")
        Dim Section2 As Section = nnreport.ReportDefinition.Sections("Section2")
        Dim PageHeaderSection1 As Section = nnreport.ReportDefinition.Sections("PageHeaderSection1")
        Dim GroupHeaderSection2 As Section = nnreport.ReportDefinition.Sections("GroupHeaderSection2")
        Dim Section3 As Section = nnreport.ReportDefinition.Sections("Section3")
        Dim ReportFooterSection2 As Section = nnreport.ReportDefinition.Sections("ReportFooterSection2")
        Dim ReportFooterSection1 As Section = nnreport.ReportDefinition.Sections("ReportFooterSection1")
        Dim height As Integer = GroupHeaderSection2.Height
        If count > 22 Then
            Dim frmPrint As New frmPrintParamater("Số dòng mỗi trang", 27, "Số dòng còn thiếu", 0)
            frmPrint.ShowDialog()
            Dim value As Integer = frmPrint.value
            value = (value * height) / count
            GroupHeaderSection2.Height += value
            Section3.Height += value * 2
        Else
            If count > 10 And count <= 19 Then
                Section1.Height += height * 2
                PageHeaderSection1.Height += height
                'Do Section1 cong them 2*GroupHeaderSection2.Height
                'Va PageHeaderSection1 cong them GroupHeaderSection2.Height
                'nen ta ko lay 22 dong cua trang dau ma lay 19 dong - count
                Dim value As Integer = 19 - count
                value = (value * height) / count
                GroupHeaderSection2.Height += value
                Section3.Height += value * 2
            ElseIf count > 19 Then
                Dim value As Integer = 22 - count
                value = (value * height) / count
                GroupHeaderSection2.Height += value
                Section3.Height += value * 2
            ElseIf count = 10 Then
                ReportFooterSection1.Height -= 278
            End If
        End If
        Dim frm As New frmReportViewer(nnreport)
        frm.ShowDialog()
    End Sub

    Public Sub ThemPhieuMoi()
        Dim frmPhieu As New frmPhieuNX
        frmPhieu.fViewPhieuNX = Me
        If enumNX = enumDoiTuong.TINHCHATNHAP Then
            frmPhieu.enumNX = enumDOITUONG.TINHCHATNHAP
        ElseIf enumNX = enumDoiTuong.TINHCHATXUAT Then
            frmPhieu.enumNX = enumDOITUONG.TINHCHATXUAT
        End If
        frmPhieu.MdiParent = Me.MdiParent
        frmPhieu.Show()
    End Sub

#Region "Context Menu"
    Private Sub mnuItemPhieuNhap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemPhieuNhap.Click
        If KiemTraChuyenDuLieu() Then
            enumNX = enumDOITUONG.TINHCHATNHAP
            ThemPhieuMoi()
        End If
    End Sub

    Private Sub mnuItemPhieuXuat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemPhieuXuat.Click
        If KiemTraChuyenDuLieu() Then
            enumNX = enumDOITUONG.TINHCHATXUAT
            ThemPhieuMoi()
        End If
    End Sub

    Private Sub mnuItemCapNhat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemCapNhat.Click
        OpenFrmPhieuNX()
    End Sub

    Private Sub mnuItemInPhieu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemInPhieu.Click
        InPhieu()
    End Sub
#End Region

    Private Sub lvDMPhieu_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvDMPhieu.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Right Then
            Dim ClickPoint As Point = New Point(e.X, e.Y)
            Dim objItem As ListViewItem = lvDMPhieu.GetItemAt(ClickPoint.X, ClickPoint.Y)
            Dim objPhieuNX As CPhieuNX = Nothing
            If objItem IsNot Nothing Then
                objPhieuNX = CPhieuNXs.GetPhieuByMa(objItem.Text)
            End If
            With ContextMenuDMPhieu
                If CUsers.isAdmin(g_User.LoginName) = False Then
                    For Each item As ToolStripItem In .Items
                        item.Visible = False
                        item.Enabled = True
                    Next
                    
                    If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
                        '.Items("mnuItemPhieuNhap").Visible = True
                        '.Items("mnuItemPhieuXuat").Visible = True
                        '.Items("ToolStripSeparator1").Visible = True
                        '.Items("mnuItemChuyenNoiBo").Visible = True
                        '.Items("ToolStripSeparator2").Visible = True
                        '.Items("mnuItemDCSLSSThua").Visible = True
                        '.Items("mnuItemDCSLSSThieu").Visible = True
                        '.Items("ToolStripSeparator3").Visible = True
                        .Items("mnuItemTCXacNhan").Visible = True
                        .Items("mnuItemTCXacNhanI").Visible = True
                        .Items("mnuItemTCXacNhanII").Visible = True
                        .Items("mnuItemTCXacNhanIII").Visible = True
                        .Items("mnuItemTCXacNhanIV").Visible = True
                        .Items("mnuItemTCHuyXacNhan").Visible = True
                        .Items("ToolStripSeparator4").Visible = True
                        .Items("mnuItemCapNhat").Visible = True
                        .Items("ToolStripSeparator5").Visible = True
                        '.Items("mnuItemXoa").Visible = True
                        '.Items("ToolStripSeparator6").Visible = True
                        .Items("mnuItemRefresh").Visible = True
                        '.Items("mnuItemInPhieu").Visible = True
                        '.Items("mnuItemExcel").Visible = True
                        '.Items("ToolStripSeparator7").Visible = True
                        '.Items("mnuItemTCXacNhanSL").Visible = True
                        '.Items("mnuItemTCHuyXacNhanSL").Visible = True

                        '.Items("ToolStripSeparator1").Visible = False
                        '.Items("ToolStripSeparator2").Visible = False
                        '.Items("ToolStripSeparator3").Visible = False
                        '.Items("ToolStripSeparator6").Visible = False
                        '.Items("mnuItemPhieuNhap").Visible = False
                        '.Items("mnuItemPhieuXuat").Visible = False
                        '.Items("mnuItemChuyenNoiBo").Visible = False
                        '.Items("mnuItemDCSLSSThua").Visible = False
                        '.Items("mnuItemDCSLSSThieu").Visible = False
                        '.Items("mnuItemXoa").Visible = False
                        '.Items("mnuItemInPhieu").Visible = False
                        '.Items("mnuItemExcel").Visible = False
                        If objItem Is Nothing Then
                            .Items("mnuItemCapNhat").Enabled = False
                            .Items("mnuItemTCXacNhan").Enabled = False
                            .Items("mnuItemTCXacNhanI").Enabled = False
                            .Items("mnuItemTCXacNhanII").Enabled = False
                            .Items("mnuItemTCXacNhanIII").Enabled = False
                            .Items("mnuItemTCXacNhanIV").Enabled = False
                            .Items("mnuItemTCHuyXacNhan").Enabled = False
                        End If
                    ElseIf g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINHSL) Then
                        '.Items("mnuItemPhieuNhap").Visible = True
                        '.Items("mnuItemPhieuXuat").Visible = True
                        '.Items("ToolStripSeparator1").Visible = True
                        '.Items("mnuItemChuyenNoiBo").Visible = True
                        '.Items("ToolStripSeparator2").Visible = True
                        '.Items("mnuItemDCSLSSThua").Visible = True
                        '.Items("mnuItemDCSLSSThieu").Visible = True
                        '.Items("ToolStripSeparator3").Visible = True
                        '.Items("mnuItemTCXacNhan").Visible = True
                        '.Items("mnuItemTCXacNhanI").Visible = True
                        '.Items("mnuItemTCXacNhanII").Visible = True
                        '.Items("mnuItemTCXacNhanIII").Visible = True
                        '.Items("mnuItemTCXacNhanIV").Visible = True
                        '.Items("mnuItemTCHuyXacNhan").Visible = True
                        '.Items("ToolStripSeparator7").Visible = True
                        .Items("mnuItemTCXacNhanSL").Visible = True
                        .Items("mnuItemTCHuyXacNhanSL").Visible = True
                        '.Items("ToolStripSeparator4").Visible = True
                        '.Items("mnuItemCapNhat").Visible = True
                        '.Items("ToolStripSeparator5").Visible = True
                        '.Items("mnuItemXoa").Visible = True
                        .Items("ToolStripSeparator6").Visible = True
                        .Items("mnuItemRefresh").Visible = True
                        '.Items("mnuItemInPhieu").Visible = True
                        '.Items("mnuItemExcel").Visible = True

                        If objItem Is Nothing Then
                            .Items("mnuItemTCXacNhanSL").Enabled = False
                            .Items("mnuItemTCHuyXacNhanSL").Enabled = False
                        End If
                    ElseIf g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
                        .Items("mnuItemPhieuNhap").Visible = True
                        .Items("mnuItemPhieuXuat").Visible = True
                        .Items("ToolStripSeparator1").Visible = True
                        .Items("mnuItemChuyenNoiBo").Visible = True
                        .Items("ToolStripSeparator2").Visible = True
                        .Items("mnuItemDCSLSSThua").Visible = True
                        .Items("mnuItemDCSLSSThieu").Visible = True
                        '.Items("ToolStripSeparator3").Visible = True
                        '.Items("mnuItemTCXacNhan").Visible = True
                        '.Items("mnuItemTCXacNhanI").Visible = True
                        '.Items("mnuItemTCXacNhanII").Visible = True
                        '.Items("mnuItemTCXacNhanIII").Visible = True
                        '.Items("mnuItemTCXacNhanIV").Visible = True
                        '.Items("mnuItemTCHuyXacNhan").Visible = True
                        '.Items("ToolStripSeparator7").Visible = True
                        '.Items("mnuItemTCXacNhanSL").Visible = True
                        '.Items("mnuItemTCHuyXacNhanSL").Visible = True
                        .Items("ToolStripSeparator4").Visible = True
                        .Items("mnuItemCapNhat").Visible = True
                        .Items("ToolStripSeparator5").Visible = True
                        .Items("mnuItemXoa").Visible = True
                        .Items("ToolStripSeparator6").Visible = True
                        .Items("mnuItemRefresh").Visible = True
                        .Items("mnuItemInPhieu").Visible = True
                        .Items("mnuItemExcel").Visible = True

                        If objItem Is Nothing Then
                            .Items("mnuItemCapNhat").Enabled = False
                            .Items("mnuItemXoa").Enabled = False
                            .Items("mnuItemInPhieu").Enabled = False
                            .Items("mnuItemExcel").Enabled = False
                        End If
                    End If
                Else 'Quyền Admin
                    For Each item As ToolStripItem In .Items
                        item.Visible = True
                        item.Enabled = True
                    Next
                End If

                'Cho ẩn hiện chức năng theo tình trạng phiếu
                '.Items("mnuItemTCXacNhan").Visible = True
                '.Items("mnuItemTCXacNhanI").Visible = True
                '.Items("mnuItemTCXacNhanII").Visible = True
                '.Items("mnuItemTCXacNhanIII").Visible = True
                '.Items("mnuItemTCXacNhanIV").Visible = True
                '.Items("mnuItemTCHuyXacNhan").Visible = True
                '.Items("ToolStripSeparator7").Visible = True
                '.Items("mnuItemTCXacNhanSL").Visible = True
                '.Items("mnuItemTCHuyXacNhanSL").Visible = True
                If objItem IsNot Nothing Then
                    'BCTH
                    If objPhieuNX.BCTH = enumBCTH.KH Then 'Nếu TCT chưa xác nhận 
                        .Items("mnuItemTCHuyXacNhan").Visible = False 'Ẩn hủy xác nhận của TCT
                    Else 'Nếu TCT xác nhận rồi
                        .Items("mnuItemTCXacNhan").Visible = False
                    End If

                    'TCSL
                    If objPhieuNX.TCSL = False Then 'Nếu TCSL chưa xác nhận
                        .Items("mnuItemTCHuyXacNhanSL").Visible = False 'Ẩn hủy xác nhận của TCSL
                    Else 'Nếu TCSL đã xác nhận
                        .Items("mnuItemTCXacNhanSL").Visible = False 'Ẩn xác nhận của TCSL
                    End If
                End If
                ' Convert from Tree coordinates to Screen coordinates 
                Dim ScreenPoint As Point = lvDMPhieu.PointToScreen(ClickPoint)
                ' Convert from Screen coordinates to Formc coordinates 
                Dim FormPoint As Point = Me.PointToClient(ScreenPoint)
                'Show context menu 
                .Show(Me, FormPoint)
            End With
        End If
    End Sub

    Private Sub mnuItemChuyenNoiBo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemChuyenNoiBo.Click
        If KiemTraChuyenDuLieu() Then
            Dim frm As New frmPhieuNXNoiBo
            frm.fViewPhieuNX = Me
            frm.MdiParent = Me.MdiParent
            frm.Show()
        End If
    End Sub

    Private Sub mnuItemXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemXoa.Click
        If MessageBox.Show("Bạn có chắc là xóa phiếu này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
            Dim objPhieu As New CPhieuNX
            objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
            If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                'Xoa phieu xuat
                objPhieu.Delete()
                If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                    objPhieu = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    If objPhieu.Delete() > 0 Then
                        RefreshForm()
                    End If
                Else
                    objPhieu = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    If objPhieu.Delete() > 0 Then
                        RefreshForm()
                    End If
                End If
            Else
                If objPhieu.Delete() > 0 Then
                    RefreshForm()
                End If
            End If
        End If
    End Sub

    Private Sub mnuItemRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemRefresh.Click
        RefreshForm()
    End Sub

#Region "Excel"
    Private Sub MnuItemExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemExcel.Click
        Dim mFileName2 As String = Application.StartupPath & "\TempPHIEUNHAPXUAT.xls"
        ToEXCEL(mFileName2)
    End Sub

    Private Sub ToEXCEL(ByVal mFileName2 As String)
        Dim objSelectedPhieu As CPhieuNX = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        Dim strSql As String
        strSql = "select * from viewNhapXuat where DPNX_ID = " & objSelectedPhieu.DPNX_ID.ToString() & _
                 " order by kho "
        Dim m_ds As DataSet
        m_ds = BaseDB.ExecSql_DataSet(strSql)

        Dim mFileName As String = Application.StartupPath & "\PHIEUNHAPXUAT.xls"

        System.IO.File.Copy(mFileName, mFileName2, True)
        Dim xlApp As Excel.Application
        Dim xlBook As Excel.Workbook
        Dim xlSheet As Excel.Worksheet
        Dim mRange As Excel.Range

        xlApp = CType(CreateObject("Excel.Application"), Excel.Application)
        xlBook = CType(xlApp.Workbooks.Open(mFileName2), Excel.Workbook)

        xlSheet = CType(xlBook.Worksheets(1), Excel.Worksheet)

        xlSheet.Activate()
        xlSheet.Application.Visible = True

        'dau phieu

        If (objSelectedPhieu.NX = "N") Then
            xlSheet.Cells(1, 5) = "PHIẾU NHẬP KHO"
            mRange = xlSheet.Cells(1, 5)
            With mRange.Font
                .Bold = True
                .Size = 24
            End With
            xlSheet.Cells(3, 2) = "Xác Nhận Đã Nhập kho"
            xlSheet.Cells(4, 4) = "Đơn vị Giao: " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, objSelectedPhieu.DVGN).Ten
            xlSheet.Cells(5, 4) = "Tính chất Nhập : " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATNHAP, objSelectedPhieu.TCNX).Ten
            xlSheet.Cells(6, 4) = "Nhập vào Kho hàng : " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.LOAIKHO, objSelectedPhieu.LK).Ten
            xlSheet.Cells(7, 4) = "Theo Hợp đồng : " + CHopDongs.GetHopDongByMa(objSelectedPhieu.HOPDONG).SOHOPDONG
            xlSheet.Cells(8, 4) = "Hóa đơn số : " + objSelectedPhieu.THEOLENH
            '
            xlSheet.Cells(4, 9) = "     Mã số : " + objSelectedPhieu.DVGN
            xlSheet.Cells(5, 9) = "     Mã số : " + objSelectedPhieu.TCNX
            xlSheet.Cells(6, 9) = "     Mã số : " + objSelectedPhieu.LK
            '
            xlSheet.Cells(1, 9) = "Số : " + objSelectedPhieu.SOPHIEU
            mRange = xlSheet.Cells(1, 9)
            With mRange.Font
                .Bold = True
                .Size = 11
            End With
            xlSheet.Cells(2, 9) = "Ngày " + CStr(objSelectedPhieu.NGAY.Day) + " Tháng " + CStr(objSelectedPhieu.NGAY.Month) + " Năm " + CStr(objSelectedPhieu.NGAY.Year)
            'xlSheet.Cells(2, 9) = objSelectedPhieu.NGAY.Date
            mRange = xlSheet.Cells(2, 9)
            With mRange
                .Font.Italic = True
                .Font.Size = 11
            End With
        Else
            xlSheet.Cells(1, 5) = "PHIẾU XUẤT KHO"
            mRange = xlSheet.Cells(1, 5)
            With mRange.Font
                .Bold = True
                .Size = 24
            End With
            xlSheet.Cells(3, 2) = "Xác Nhận Thanh Toán"
            xlSheet.Cells(4, 4) = "Đơn vị Nhận: " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, objSelectedPhieu.DVGN).Ten
            xlSheet.Cells(5, 4) = "Tính chất Xuất : " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATXUAT, objSelectedPhieu.TCNX).Ten
            xlSheet.Cells(6, 4) = "Xuất từ Kho hàng : " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.LOAIKHO, objSelectedPhieu.LK).Ten
            xlSheet.Cells(7, 4) = "Theo chỉ lệnh : " + objSelectedPhieu.THEOLENH
            xlSheet.Cells(8, 4) = "Người Nhận : " + objSelectedPhieu.NGUOIGN
            xlSheet.Cells(7, 8) = "Giá Trị Phiếu : " + objSelectedPhieu.NGAYPH
            mRange = xlSheet.Cells(7, 8)
            With mRange
                .NumberFormat = FormatDateStyle()
            End With
            xlSheet.Cells(8, 8) = "Giấy Giới Thiệu Số : " + objSelectedPhieu.GGT
            '
            xlSheet.Cells(4, 9) = "     Mã số : " + objSelectedPhieu.DVGN
            xlSheet.Cells(5, 9) = "     Mã số : " + objSelectedPhieu.TCNX
            xlSheet.Cells(6, 9) = "     Mã số : " + objSelectedPhieu.LK
            '
            xlSheet.Cells(1, 9) = "Số : " + objSelectedPhieu.SOPHIEU
            mRange = xlSheet.Cells(1, 9)
            With mRange.Font
                .Bold = True
            End With
            xlSheet.Cells(2, 9) = "Ngày " + CStr(objSelectedPhieu.NGAY.Day) + " Tháng " + CStr(objSelectedPhieu.NGAY.Month) + " Năm " + CStr(objSelectedPhieu.NGAY.Year)
            mRange = xlSheet.Cells(2, 9)
            With mRange
                .Font.Italic = True
                .Font.Size = 11
            End With

        End If

        Dim iRow0 As Integer = 16
        Dim len, i, j, stt As Integer
        Dim ten_thuoc, ma, code, lo_hang, dvt, h, hsd, ghi_chu, kho_hang As String
        Dim slth, slkh, don_gia, thanh_tien As Double

        Dim rowIndex As Integer 'Luu lai index cua dong can lam viec

        '(i chay trong ds, j chay trong excel)
        i = 0
        j = 0

        'add so thu tu vao excel
        stt = 1

        len = m_ds.Tables(0).Rows.Count

        While (i < len)
            If (i >= len) Then
                Exit While
            End If
            'Hien thi kho
            kho_hang = m_ds.Tables(0).Rows.Item(i).Item("kho")
            xlSheet.Cells(iRow0 + j, 2) = kho_hang + "  " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.KHO, kho_hang).Ten
            mRange = xlSheet.Cells(iRow0 + j, 2)
            With mRange
                .Font.Underline = True
                .Font.Bold = True
                .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            End With
            'insert row tuong ung voi kho
            j += 1
            mRange = xlSheet.Rows(iRow0 + j)
            mRange.Insert(Shift:=Excel.XlInsertShiftDirection.xlShiftDown)
            mRange = xlSheet.Rows(iRow0 + j)
            With mRange
                .Font.Underline = False
                .Font.Bold = False
                .HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft
            End With

            'group theo Kho Hang
            While (m_ds.Tables(0).Rows.Item(i).Item("kho") = kho_hang)
                ten_thuoc = m_ds.Tables(0).Rows.Item(i).Item("ten")
                ma = m_ds.Tables(0).Rows.Item(i).Item("ma")
                code = m_ds.Tables(0).Rows.Item(i).Item("code")
                lo_hang = ChuanHoaChuoi(m_ds.Tables(0).Rows.Item(i).Item("lo"))
                don_gia = m_ds.Tables(0).Rows.Item(i).Item("gle")
                dvt = m_ds.Tables(0).Rows.Item(i).Item("dvt")
                hsd = ChuanHoaChuoi(m_ds.Tables(0).Rows.Item(i).Item("hansd"))
                h = ChuanHoaChuoi(m_ds.Tables(0).Rows.Item(i).Item("h"))
                slth = m_ds.Tables(0).Rows.Item(i).Item("SLTH")
                slkh = m_ds.Tables(0).Rows.Item(i).Item("SLKH")
                ghi_chu = ChuanHoaChuoi(m_ds.Tables(0).Rows.Item(i).Item("GHICHU"))
                thanh_tien = m_ds.Tables(0).Rows.Item(i).Item("THANHTIEN")

                xlSheet.Cells(iRow0 + j, 1) = stt
                xlSheet.Cells(iRow0 + j, 2) = " " + ten_thuoc + Chr(10) + "  " + ma + "    " + lo_hang
                xlSheet.Cells(iRow0 + j, 3) = dvt
                xlSheet.Cells(iRow0 + j, 4) = h
                xlSheet.Cells(iRow0 + j, 5) = hsd.ToString()
                mRange = xlSheet.Cells(iRow0 + j, 5)

                'Han su dung
                'Do hsd co kieu la 01/09 nhung khi luu sang file excell no se
                'chuyen thanh 09/01/2007 nen formatnumber se la 'MM/dd'
                With mRange
                    .NumberFormat = "MM/dd"
                End With
                xlSheet.Cells(iRow0 + j, 6) = slkh
                mRange = xlSheet.Cells(iRow0 + j, 6)
                With mRange
                    .HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
                    If IsSoChan(slkh) Then
                        .NumberFormat = "#,###"
                    Else
                        .NumberFormat = FormatQuantityStyle()
                    End If
                End With

                'Slkh
                xlSheet.Cells(iRow0 + j, 7) = slkh
                mRange = xlSheet.Cells(iRow0 + j, 7)
                With mRange
                    .HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
                    If IsSoChan(slkh) Then
                        .NumberFormat = "#,###"
                    Else
                        .NumberFormat = FormatQuantityStyle()
                    End If
                End With

                'Don Gia
                xlSheet.Cells(iRow0 + j, 8) = don_gia
                mRange = xlSheet.Cells(iRow0 + j, 8)
                With mRange
                    .HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
                    If IsSoChan(don_gia) Then
                        .NumberFormat = "#,###"
                    Else
                        .NumberFormat = FormatQuantityStyle()
                    End If
                End With

                'Thanh tien
                xlSheet.Cells(iRow0 + j, 9) = thanh_tien
                mRange = xlSheet.Cells(iRow0 + j, 9)
                With mRange
                    .HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
                    If IsSoChan(thanh_tien) Then
                        .NumberFormat = "#,###"
                    Else
                        .NumberFormat = FormatQuantityStyle()
                    End If
                End With

                'Ghi chu
                xlSheet.Cells(iRow0 + j, 10) = " " + ghi_chu
                '
                i += 1
                stt += 1
                If (i >= len) Then
                    Exit While
                End If
                'insert row tuong ung voi mat hang
                j += 1
                mRange = xlSheet.Rows(iRow0 + j)
                mRange.Insert(Shift:=Excel.XlInsertShiftDirection.xlShiftDown)
            End While
        End While

        Dim iRowsCount = j
        Dim mColsCount = 10
        'AlignCenter for col1 
        mRange = xlSheet.Range(xlSheet.Cells(iRow0 - 1, 1), xlSheet.Cells(iRow0 + iRowsCount, 1))
        With mRange
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            .VerticalAlignment = Excel.XlVAlign.xlVAlignTop
        End With
        'AlignCenter for from col3 to col5
        mRange = xlSheet.Range(xlSheet.Cells(iRow0 - 1, 3), xlSheet.Cells(iRow0 + iRowsCount, 5))
        With mRange
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
        End With

        'AlignCenter for mColsCount
        mRange = xlSheet.Range(xlSheet.Cells(iRow0 - 1, mColsCount), xlSheet.Cells(iRow0 + iRowsCount, mColsCount))
        With mRange
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft
            .VerticalAlignment = Excel.XlVAlign.xlVAlignTop
        End With

        'Ve line Border cho danh muc cac mat hang
        mRange = xlSheet.Range(xlSheet.Cells(iRow0 - 1, 1), xlSheet.Cells(iRow0 + iRowsCount + 4, mColsCount))
        With mRange.Borders(Excel.XlBordersIndex.xlEdgeLeft)
            .LineStyle = Excel.XlLineStyle.xlContinuous
            .Weight = Excel.XlBorderWeight.xlThin
        End With
        With mRange.Borders(Excel.XlBordersIndex.xlEdgeTop)
            .LineStyle = Excel.XlLineStyle.xlContinuous
            .Weight = Excel.XlBorderWeight.xlThin
        End With
        With mRange.Borders(Excel.XlBordersIndex.xlEdgeRight)
            .LineStyle = Excel.XlLineStyle.xlContinuous
            .Weight = Excel.XlBorderWeight.xlThin
        End With

        'Aglignment cho cac col slkh,slth,gle,thanhtien
        mRange = xlSheet.Range(xlSheet.Cells(iRow0 - 1, 6), xlSheet.Cells(iRow0 + iRowsCount + 1, mColsCount - 1))
        With mRange
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
            .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
        End With
        '
        'Merge col8 va col9 cho Tong gia tri
        '
        rowIndex = iRow0 + iRowsCount + 2 'Row cua Tong Gia tri
        mRange = xlSheet.Range(xlSheet.Cells(rowIndex, 8), xlSheet.Cells(rowIndex, 9))
        With mRange
            .Merge()
            .Font.Size = 10
            .Font.Bold = True
        End With
        'Tao gach phia tren Tong gia tri
        mRange = xlSheet.Range(xlSheet.Cells(rowIndex, 7), xlSheet.Cells(rowIndex, 9))
        With mRange.Borders(Excel.XlBordersIndex.xlEdgeTop)
            .LineStyle = Excel.XlLineStyle.xlDashDotDot
            .Weight = Excel.XlBorderWeight.xlThin
        End With
        'Show Tong gia tri
        xlSheet.Cells(rowIndex, 7) = "Cộng : "
        xlSheet.Cells(rowIndex, 8) = objSelectedPhieu.TGIATRI
        mRange = xlSheet.Cells(rowIndex, 8)
        With mRange
            If IsSoChan(objSelectedPhieu.TGIATRI) Then
                .NumberFormat = "#,###"
            Else
                .NumberFormat = FormatQuantityStyle()
            End If
        End With
        '
        'Phia duoi bao cao phieu nhap xuat
        rowIndex = iRow0 + iRowsCount + 6
        xlSheet.Cells(rowIndex, 2) = "Tổng cộng : " + CStr(objSelectedPhieu.SOKH) + " khoản"
        xlSheet.Cells(rowIndex, 5) = "Số kiện : " + objSelectedPhieu.SOKIEN.ToString(FormatQuantityStyle())
        xlSheet.Cells(rowIndex, 7) = "Trọng lượng : " + objSelectedPhieu.TRLUONG.ToString(FormatQuantityStyle()) + "    kg"

        xlSheet.Cells(rowIndex + 1, 2) = "Thành tiền : " + objSelectedPhieu.TGIATRI.ToString(FormatMoneyStyle()) + "   Bằng chữ : " + DoiSoRaChu(objSelectedPhieu.TGIATRI)
        xlSheet.Cells(rowIndex + 2, 2) = "Đã nhận đủ hàng     Ngày    tháng    năm      "
        'Chinh lai font chu cho cac COL 2 Tong cong, So kien, Trong luong, Thanhtien, Da nhan du hang
        mRange = xlSheet.Range(xlSheet.Cells(rowIndex, 2), xlSheet.Cells(rowIndex + 2, 7))
        With mRange
            .Font.Size = 9
        End With

        'Tao col va show data cho dong "Thu Kho   Nguoi Giao nhan     Nguoi viet phieu   Thu truong don vi"
        rowIndex = iRow0 + iRowsCount + 10
        xlSheet.Range(xlSheet.Cells(rowIndex, 2), xlSheet.Cells(rowIndex, 10)).Merge()
        xlSheet.Range(xlSheet.Cells(rowIndex, 2), xlSheet.Cells(rowIndex, 10)).Font.Bold = True
        xlSheet.Cells(rowIndex, 2) = "Thủ Kho                               Người Giao             Người Viết Phiếu               Thủ Trưởng Đơn Vị"
        rowIndex = iRow0 + iRowsCount + 14
        xlSheet.Cells(rowIndex, 3) = objSelectedPhieu.NGUOIGN
        xlSheet.Cells(rowIndex, 6) = objSelectedPhieu.NGUOIVP
        xlSheet.Range(xlSheet.Cells(rowIndex, 6), xlSheet.Cells(rowIndex, 7)).Merge()
        mRange = xlSheet.Range(xlSheet.Cells(rowIndex, 1), xlSheet.Cells(rowIndex, mColsCount))
        With mRange
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            .VerticalAlignment = Excel.XlHAlign.xlHAlignCenter
        End With

        xlBook.Save()
        xlApp.ActiveWindow.Visible = False
        xlApp.Windows(1).Activate()
    End Sub
#End Region

    Private Sub mnuItemDCSLSSThua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemDCSLSSThua.Click
        If KiemTraChuyenDuLieu() Then
            enumNX = enumDOITUONG.TINHCHATNHAP
            Dim frmPhieu As New frmPhieuNXDCSS
            frmPhieu.enumNX = enumNX
            frmPhieu.fViewPhieuNX = Me
            frmPhieu.MdiParent = Me.MdiParent
            frmPhieu.Show()
        End If
    End Sub

    Private Sub mnuItemDCSLSSThieu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemDCSLSSThieu.Click
        If KiemTraChuyenDuLieu() Then
            enumNX = enumDOITUONG.TINHCHATXUAT
            Dim frmPhieu As New frmPhieuNXDCSS
            frmPhieu.enumNX = enumNX
            frmPhieu.fViewPhieuNX = Me
            frmPhieu.MdiParent = Me.MdiParent
            frmPhieu.Show()
        End If
    End Sub

    Private Sub txtNX_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtNX.KeyDown
        isMaxCharNum = False
        If e.KeyCode = Keys.Enter Then
            Dim lvItem As ListViewItem
            Dim obj As CPhieuNX
            If txtNX.Text = "N" Then
                obj = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, txtSoPhieu.Text)
            ElseIf txtNX.Text = "X" Then
                obj = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, txtSoPhieu.Text)
            Else
                ShowMessages("Loại phiếu không hợp lệ")
                Exit Sub
            End If
            If obj IsNot Nothing Then
                mDpnx_Id = obj.DPNX_ID
                lvItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        Else
            If txtNX.Text.Length = 1 Or (e.KeyCode <> Keys.N And e.KeyCode <> Keys.X) Then
                If e.KeyCode <> Keys.Back Then
                    isMaxCharNum = True
                End If
            End If
        End If
    End Sub

    Private Sub txtNX_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtNX.KeyPress
        If isMaxCharNum = True Then
            e.Handled = True
        Else
            e.KeyChar = Char.Parse(StrConv(e.KeyChar.ToString(), VbStrConv.Uppercase))
        End If
    End Sub

    Private Sub txtSoPhieu_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSoPhieu.KeyDown
        If e.KeyCode = Keys.Enter Then
            Dim lvItem As ListViewItem
            Dim obj As CPhieuNX
            If txtNX.Text = "N" Then
                obj = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, txtSoPhieu.Text)
            ElseIf txtNX.Text = "X" Then
                obj = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, txtSoPhieu.Text)
            Else
                ShowMessages("Loại phiếu không hợp lệ")
                Exit Sub
            End If
            If obj IsNot Nothing Then
                mDpnx_Id = obj.DPNX_ID
                lvItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    Private Sub txtSoPhieu_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSoPhieu.KeyPress
        'Viet hoa cac ky tu go
        e.KeyChar = Char.Parse(StrConv(e.KeyChar.ToString(), VbStrConv.Uppercase))
    End Sub

    Private Sub mnuItemTCXacNhan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles mnuItemTCXacNhan.Click, mnuItemTCXacNhanI.Click, mnuItemTCXacNhanII.Click, mnuItemTCXacNhanIII.Click, mnuItemTCXacNhanIV.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        If sender Is mnuItemTCXacNhan Then
            objPhieu.KYQT = 1 'Chua quyet toan
        ElseIf sender Is mnuItemTCXacNhanI Then
            objPhieu.KYQT = 2 'Quy I
        ElseIf sender Is mnuItemTCXacNhanII Then
            objPhieu.KYQT = 3 'Quy II
        ElseIf sender Is mnuItemTCXacNhanIII Then
            objPhieu.KYQT = 4 'Quy III
        ElseIf sender Is mnuItemTCXacNhanIV Then
            objPhieu.KYQT = 5 'Quy IV
        End If
        'Neu da xac nhan roi (BCTH = 2) thi chi cap nhat dpnx cho giá trị kỳ quyết toán
        If objPhieu.BCTH = enumPHANQUYEN.BANTAICHINH Then
            If objPhieu.Update() > 0 Then
                'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    'Xác nhận phiếu còn lại
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.KYQT = objPhieu.KYQT
                    objPhieuTemp.Update()
                End If
                RefreshForm()
            End If
        Else
            'Nguoc lai thi goi function TaiChinhXacNhan de cap nhat lai slth va sltonth
            If objPhieu.TaiChinhXacNhan() > 0 Then
                'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    'Xác nhận phiếu còn lại
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.KYQT = objPhieu.KYQT
                    objPhieuTemp.TaiChinhXacNhan()
                End If
                RefreshForm()
                Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    Private Sub mnuItemTCHuyXacNhan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemTCHuyXacNhan.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        If objPhieu.BCTH = enumPHANQUYEN.BANTAICHINH Then
            If objPhieu.TaiChinhHuyXacNhan() > 0 Then
                'Kiem tra neu la NX Noi bo thi cap nhat phieu con lai
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieu = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieu = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieu.TaiChinhHuyXacNhan()
                End If
                RefreshForm()
                Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    Private Sub txtSoPhieu_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSoPhieu.TextChanged

    End Sub

    Private Sub mnuItemTCXacNhanSL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemTCXacNhanSL.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        'Neu chưa xac nhan thi chi cap nhat dpnx cho giá trị TCSL (tài chính số lượng) = true
        If objPhieu.TCSL = False Then
            If objPhieu.TaiChinhXacNhanSL() > 0 Then
                'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    'Xác nhận phiếu còn lại
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.TaiChinhXacNhanSL()
                End If
                RefreshForm()
                Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    Private Sub mnuItemTCHuyXacNhanSL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemTCHuyXacNhanSL.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        'Neu đã xac nhan thi chi cap nhat dpnx cho giá trị TCSL (tài chính số lượng) = false
        If objPhieu.TCSL = True Then
            If objPhieu.TaiChinhHuyXacNhanSL() > 0 Then
                'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    'Xác nhận phiếu còn lại
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.TaiChinhHuyXacNhanSL()
                End If
                RefreshForm()
                Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub
End Class